package com.face.receive.jsu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.face.bean.jsu.FindPopulation;
import com.face.common.jsu.FindFaceSetOutid;
import com.face.common.jsu.LostFaceSetOutid;
import com.face.common.jsu.Rename;
import com.face.operate.jsu.FindToken_Operate;
import com.face.operate.jsu.LostMessage;
import com.face.operate.jsu.LostToken_Operate;
import com.face.operate.jsu.Face_Operate;

;

/**
 * Servlet implementation class ReceiveImg
 */
/*
 * 接收走失人员家属上传图片 返回最相似的热心人士上传的照片集
 */
@WebServlet("/ReceiveImg")
public class ReceiveLost extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ServletFileUpload upload;
	private final long MAXSize = 4194304 * 2L;// 4*2MB
	// 热心人士提供照片合集id
	LostFaceSetOutid lostFaceSetOutid = LostFaceSetOutid.getInstance();
	String faceset_outid1 = lostFaceSetOutid.getLostFaceSetID();
	// 走失人口家属提供照片合集id
	FindFaceSetOutid findFaceSetOutid = FindFaceSetOutid.getInstance();
	String faceset_outid2 = findFaceSetOutid.getFindFaceSetID();
	
	String findtUrl = "http://47.106.35.203:8080/find/";
	String saveDir = "/root/lost/";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public void init(ServletConfig config) throws ServletException {

		FileItemFactory factory = new DiskFileItemFactory();
		this.upload = new ServletFileUpload(factory);
		this.upload.setSizeMax(this.MAXSize);
		this.upload.setHeaderEncoding("UTF-8");
		// filedir = config.getServletContext().getRealPath("images");
		// System.out.println("filedir=" + filedir);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String filename = "";
		String filepath = "";
		JSONObject json = new JSONObject();
		JSONArray array = new JSONArray();
		Map<String, String> map = new HashMap<>();
		Map<String, String> fileMap = new HashMap<>();
		List<String> list = new ArrayList<>();
		try {
			List<FileItem> items = this.upload
					.parseRequest(new ServletRequestContext(request));
			if (items != null && !items.isEmpty()) {
				for (FileItem fileItem : items) {
					if (fileItem.isFormField()) {
						String inputName = fileItem.getFieldName();
						String inputValue = new String(
								fileItem.getString("UTF-8"));
						map.put(inputName, inputValue);
						System.out.println(inputName + ":" + inputValue);
					} else {
						filename = Rename.rename();
						filepath = saveDir + filename;
						fileMap.put(filename, filepath);
						System.out.println("文件保存路径为:" + filepath);
						File file = new File(filepath);
						InputStream inputSteam = fileItem.getInputStream();
						BufferedInputStream fis = new BufferedInputStream(
								inputSteam);
						FileOutputStream fos = new FileOutputStream(file);
						int f;
						while ((f = fis.read()) != -1) {
							fos.write(f);
						}
						fos.flush();
						fos.close();
						fis.close();
						inputSteam.close();
						System.out.println("文件：" + filename + "上传成功!");
					}

				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			System.out.println("上传失败");
		}

		Face_Operate face = new Face_Operate();
		// face.delete_faceset("lost");
		// face.create_faceset("lost");
		// face.create_faceset(faceset_outid1);
		// face.create_faceset(faceset_outid2);

		for (Object obj : fileMap.keySet()) {

			filename = (String) obj;
			filepath = fileMap.get(filename);

			byte[] fb = face.toByteArray(filepath);
			// 提取人脸信息，返回识别码
			String facetoken = face.toFaceToken(fb);

			try {
				if (!facetoken.equals("failed")) {
					// System.out.println("检测失败");
					// json.put("message", "invalid");
					// } else {
					// json.put("message", "ok");
					// 搜索faceset并且给出最相似的两个facetoken封装成List
					FindToken_Operate tok1 = new FindToken_Operate();
					List<String> faceList = face.search_faceset(fb, facetoken,
							faceset_outid1);
					// if (faceList.size() == 0) {
					// json.put("findMessage", "notFound");
					// System.out.println("没有找到相似图片");
					// }
					for (int i = 0; i < faceList.size(); i++) {
						String faceId = faceList.get(i);
						if (!list.contains(faceId)) {
							list.add(faceId);
							FindPopulation find = tok1.selectByfaceId(faceId);
							if (find != null) {
								System.out.println("查询到的第" + i + "bean:"
										+ find.toString());
								JSONObject js = new JSONObject();
								js.put("url", find.getFacepath());
								String thecity = find.getCity();
								System.out.println(thecity);
								if (thecity.equals("null")) {
									js.put("location", find.getProvince()
											+ find.getLocation());
								} else {
									js.put("location",
											find.getProvince() + find.getCity()
													+ find.getLocation());
								}
								js.put("time", find.getTimestamp());
								js.put("message", find.getMessage());
								array.put(js);
							} else {
								System.out.println("查无结果");
							}
						}
					}

					LostToken_Operate tok2 = new LostToken_Operate();
					System.out.println("username的值：" + map.get("username"));
					tok2.Save(map.get("username"), map.get("name"), facetoken,
							filename);

					// 将人脸标识放入容器
					face.add_faceset(facetoken, faceset_outid2);
				} else {
					File file = new File(filepath);
					if (file.exists() && file.isFile()) {
						file.delete();
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		try {
			if (array.length() != 0) {
				json.put("photo", array);
			} else {
				json.put("findMessage", "notFound");
				System.out.println("没有找到相似图片");
			}
		} catch (Exception e) {

		}
		LostMessage lostMessage = new LostMessage();
		lostMessage.save(map);
		response.setContentType("application/json; charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(json.toString());
		System.out.println("返回的json数据：" + json.toString());

	}

}
